﻿using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;

namespace MyAssetBundles {
    public abstract class MonoFolder : MonoBehaviour, IEnumerable, IEnumerable<KeyValuePair<string, MyFileInfo>> {
        private Dictionary<string, MyFileInfo> _fileDictionary = new Dictionary<string, MyFileInfo>();
        private List<string> _autoDeleteFiles = new List<string>();
        public int Count
        {
            get {
                return _fileDictionary.Count;
            }
        }

        public MyFileInfo GetValue (string key)
        {
            MyFileInfo info = null;
            _fileDictionary.TryGetValue(key, out info);
            return info;
        }

        public void Add (string key, MyFileInfo value)
        {
            _fileDictionary.Add(key, value);
        }

        protected void AddAutoDeleteFile (string path)
        {
            _autoDeleteFiles.Add(path);
        }

        protected virtual void Reset ()
        {
            _fileDictionary.Clear();
        }

        protected virtual void OnClean ()
        {

        }

        public void OnDestroy ()
        {
            OnClean();
            foreach (var path in _autoDeleteFiles)
            {
                if (File.Exists(path))
                    File.Delete(path);
            }
            _autoDeleteFiles.Clear();
        }
        
        public IEnumerator<KeyValuePair<string, MyFileInfo>> GetEnumerator ()
        {
            return ((IEnumerable<KeyValuePair<string, MyFileInfo>>)_fileDictionary).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator ()
        {
            return ((IEnumerable<KeyValuePair<string, MyFileInfo>>)_fileDictionary).GetEnumerator();
        }
    }

    public class FolderMgr {
        protected static List<MonoFolder> _baseList = new List<MonoFolder>();
        public static T Create<T> () where T : MonoFolder, new()
        {
            var t = new T();
            _baseList.Add(t);
            return t;
        }

        public static void DestroyAll ()
        {
            if (_baseList == null || _baseList.Count == 0) return;
#if UNITY_EDITOR
            for (int i = 0; i < _baseList.Count; i++)
                _baseList[i].OnDestroy();
#endif
            _baseList.Clear();
            FolderProgress.ClearProgress();
        }
    }
}

